package com.skyline.wo.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.skyline.base.dao.impl.BaseDaoImpl;
import com.skyline.base.type.Activity;
import com.skyline.common.bean.Page;
import com.skyline.common.cache.annotation.Cache;
import com.skyline.common.cache.annotation.CacheCategoryType;
import com.skyline.common.cache.annotation.CacheDelete;
import com.skyline.common.cache.annotation.Fk;
import com.skyline.common.cache.annotation.Param;
import com.skyline.wo.dao.AlbumDao;
import com.skyline.wo.mapper.AlbumMapper;
import com.skyline.wo.model.Album;

//TODO:加注释
@Repository("albumDao")
public class AlbumDaoImpl extends BaseDaoImpl implements AlbumDao {
	/**
	 * select id,userId,userNick,albumName,picCount,commentCount ,visitCount
	 * ,upCount
	 * ,downCount,shareCount,cover,coverExt,createDate,updateDate,authority
	 * ,activity from album where id=? limit 1;
	 * */
	@Value("${AlbumDao.queryAlbumById}")
	private String queryAlbumByIdSql;

	/**
	 * select
	 * id,userId,userNick,albumName,place,description,picCount,commentCount
	 * ,visitCount
	 * ,upCount,downCount,shareCount,cover,coverExt,createDate,updateDate
	 * ,authority ,activity from album where id=? limit 1;
	 * */
	@Value("${AlbumDao.queryAlbumById}")
	private String queryAlbumDetailByIdSql;

	/**
	 *select
	 * id,userId,userNick,albumName,place,description,picCount,commentCount
	 * ,visitCount
	 * ,upCount,downCount,shareCount,cover,coverExt,createDate,updateDate
	 * ,authority ,activity from album where userId=? and authority<=? and
	 * (activity=? or activity=?)
	 * */
	@Value("${AlbumDao.queryAlbumDetailsByUserIdWithPortrait}")
	private String queryAlbumDetailsByUserIdWithPortraitSql;

	/**
	 *select id,userId,userNick,albumName,picCount,commentCount ,visitCount
	 * ,upCount
	 * ,downCount,shareCount,cover,coverExt,createDate,updateDate,authority
	 * ,activity from album where userId=? and authority<=? and activity=?
	 * */
	@Value("${AlbumDao.queryAlbumsByUserIdWithoutPortrait}")
	private String queryAlbumsByUserIdWithoutPortraitSql;

	/**
	 * update album set visitCount=visitCount+? where id=?
	 * */
	@Value("${AlbumDao.updateVisitCount}")
	private String updateVisitCountSql;

	/**
	 * update album set
	 * albumName=?,place=?,description=?,authority=?,updateTime=timestamp where
	 * id=? and ownerId=?
	 * */
	@Value("${AlbumDao.updateAlbumInfo}")
	private String updateAlbumInfoSql;

	/**
	 * insert into
	 * album(albumName,authority,ownerId,ownerPortrait,ownerNickname,
	 * createTime,updateTime
	 * ,commentNum,shareNum,visitNum,activity,up,down,cover,coverExt,
	 * place,description,photoNum) values
	 * (?,?,?,?,?,current_timestamp,current_timestamp,0,0,0,?,0,0,?,?,?,?,0)
	 * */
	@Value("${AlbumDao.insertAlbumReturnId}")
	private String insertAlbumReturnIdSql;

	/**
	 * update album set activity=? where id=?
	 * */
	@Value("${AlbumDao.updateAlbumActivity}")
	private String updateAlbumActivitySql;

	/**
	 * update album set photoNum=photoNum+? where id=?
	 * */
	@Value("${AlbumDao.updatePhotoCount}")
	private String updatePhotoCountSql;

	/**
	 * update album set cover=?,coverExt=? where id=?
	 * */
	@Value("${AlbumDao.updateAlbumCover}")
	private String updateAlbumCoverSql;

	/**
	 *update album set cover=ifnull((select smallfile from photo where id !=?
	 * and albumId=? and (activity=? or activity=?) order by orderNo,id desc
	 * limit 1),?),coverExt=ifnull((select ext from photo where id !=? and
	 * albumId=? and (activity=? or activity=?) order by orderNo,id desc limit
	 * 1),?),photoNum=photoNum+? where id=?
	 * */
	@Value("${AlbumDao.updateRandomCoverAndPhotoCount}")
	private String updateRandomCoverAndPhotoCountSql;

	/**
	 * select id,albumName,photoNum,cover,coverExt from album where ownerId=?
	 * and activity=? order by id desc
	 * */
	@Value("${AlbumDao.queryAlbumNamesOfUser}")
	private String queryAlbumNamesOfUserSql;

	/**
	 * select
	 * id,ownerId,ownerNickname,ownerPortrait,albumName,photoNum,commentNum
	 * ,visitNum
	 * ,up,down,shareNum,cover,coverExt,createTime,updateTime,authority,activity
	 * from album where ownerId=? and activity=?
	 * */
	@Value("${AlbumDao.queryUserAlbumByActivity}")
	private String queryUserAlbumByActivitySql;

	// @Value("${AlbumDao.insertAlbumReturnId}")
	// private String insertAlbumReturnId;
	// /**
	// * select
	// * id,userId,userNick,albumName,place,description,picCount,commentCount
	// * ,visitCount
	// *
	// ,upCount,downCount,shareCount,cover,coverExt,createDate,updateDate,authority
	// * ,activity from album where userId=? and id=? limit 1;
	// * */
	// @Value("${AlbumDao.queryUserAlbumDetailOfId}")
	// private String queryUserAlbumDetailOfIdSql;
	//
	// /**
	// * select
	// * id,userId,userNick,albumName,picCount,commentCount,visitCount,upCount
	// *
	// ,downCount,shareCount,cover,coverExt,createDate,updateDate,authority,activity
	// from
	// * album where userId=? and id=? limit 1;
	// * */
	// @Value("${AlbumDao.queryUserAlbumOfId}")
	// private String queryUserAlbumOfIdSql;

	// /**
	// * count(1) from album where userId=? and id=?
	// * */
	// @Value("${AlbumDao.countUserAlbumOfId}")
	// private String countUserAlbumOfIdSql;

	// /**
	// * select
	// * id,userId,userNick,albumName,place,description,picCount,commentCount
	// * ,visitCount
	// *
	// ,upCount,downCount,shareCount,cover,coverExt,createDate,updateDate,authority
	// * ,activity from album where userId=? and authority<=? and activity=?
	// * */
	// @Value("${AlbumDao.queryActiveAlbumsByUserId}")
	// private String queryActiveAlbumsByUserIdSql;

	// @Value("${AlbumDao.updateAlbumInfo}")
	// private String updateAlbumInfoSql;
	//	
	// @Value("${AlbumDao.updateAlbumActivity}")
	// private String updateAlbumActivitySql;

	// /**
	// * select
	// * id,userId,userNick,albumName,picCount,commentCount,visitCount,upCount
	// *
	// ,downCount,shareCount,cover,coverExt,createDate,updateDate,authority,activity
	// from
	// * album where id=? limit 1;
	// * */
	// @Value("${AlbumDao.queryAlbumById}")
	// private String queryAlbumByIdSql;

	// /**
	// * update album set photoNum=photoNum-? where id=?
	// * */
	// @Value("${AlbumDao.updatePhotoCountDec}")
	// private String updatePhotoCountDecSql;

	@CacheDelete(type = CacheCategoryType.ALBUM)
	public void updateVisitCount(@Fk long userId, long albumId, int addedCount) {
		jdbcTemplate.update(updateVisitCountSql, addedCount, albumId);
	}

	@Cache(keyPattern = "album-:id", type = CacheCategoryType.ALBUM)
	public Album queryAlbumById(@Param("id") long albumId) {
		List<Album> albums = jdbcTemplate.query(queryAlbumByIdSql, AlbumMapper.getMapper(), albumId);
		if (albums.isEmpty()) {
			return null;
		} else {
			return albums.get(0);
		}
	}

	@Cache(keyPattern = "album-d-:id", type = CacheCategoryType.ALBUM)
	public Album queryAlbumDetailById(@Param("id") long albumId) {
		List<Album> albums = jdbcTemplate.query(queryAlbumDetailByIdSql, AlbumMapper.getMapper(), albumId);
		if (albums.isEmpty()) {
			return null;
		} else {
			return albums.get(0);
		}
	}

	@Cache(keyPattern = "album-l-face-u:uid-auth:auth", type = CacheCategoryType.ALBUM, pagination = true)
	public List<Album> queryAlbumDetailsByUserIdWithPortrait(@Param("uid") @Fk long userId,
			@Param("auth") int authority, Page page) {
		if (page == null) {
			return jdbcTemplate.query(queryAlbumDetailsByUserIdWithPortraitSql, AlbumMapper.getMapper(), userId,
					authority, Activity.NORMAL.toString(), Activity.UNDELETABLE.toString());
		}
		return this.getPaginationResult(queryAlbumDetailsByUserIdWithPortraitSql, page, AlbumMapper.getMapper(),
				userId, authority, Activity.NORMAL.toString(), Activity.UNDELETABLE.toString());
	}

	@CacheDelete(type = CacheCategoryType.ALBUM)
	public void updateAlbumInfo(@Fk long userId, long albumId, String albumName, String place, String description,
			int authority) {
		jdbcTemplate.update(updateAlbumInfoSql, albumName, place, description, authority, albumId, userId);
	}

	@CacheDelete(type = CacheCategoryType.ALBUM)
	public long insertAlbumReturnId(@Fk long ownerId, String ownerNickname, String ownerPortrait, String albumName,
			String place, String description, int authority, Activity activity, String cover, String coverExt) {
		return insertWithIdReturn(insertAlbumReturnIdSql, albumName, authority, ownerId, ownerPortrait, ownerNickname,
				activity.toString(), cover, coverExt, place, description);
	}

	@CacheDelete(type = CacheCategoryType.ALBUM)
	public void updateAlbumActivity(@Fk long userId, long albumId, Activity activity) {
		jdbcTemplate.update(updateAlbumActivitySql, activity.toString(), albumId);
	}

	@CacheDelete(type = CacheCategoryType.ALBUM)
	public void updatePhotoCount(@Fk long userId, long albumId, int addedCount) {
		jdbcTemplate.update(updatePhotoCountSql, addedCount, albumId);
	}

	@CacheDelete(type = CacheCategoryType.ALBUM)
	public void updateAlbumCover(@Fk long userId, long albumId, String cover, String coverExt) {
		jdbcTemplate.update(updateAlbumCoverSql, cover, coverExt, albumId);
	}

	@CacheDelete(type = CacheCategoryType.ALBUM)
	public void updateRandomCoverAndPhotoCount(@Fk long userId, long albumId, long oldPhotoId, String defaultCover,
			String defaultCoverExt, int decCount) {
		String normal = Activity.NORMAL.toString();
		String undeletable = Activity.UNDELETABLE.toString();
		jdbcTemplate.update(updateRandomCoverAndPhotoCountSql, oldPhotoId, albumId, normal, undeletable, defaultCover,
				oldPhotoId, albumId, normal, undeletable, defaultCoverExt, decCount, albumId);
	}

	@Cache(keyPattern = "album-l-noface-u:uid-auth:auth", type = CacheCategoryType.ALBUM, pagination = true)
	public List<Album> queryAlbumsByUserIdWithoutPortrait(@Param("uid") @Fk long userId, @Param("auth") int authority,
			Page page) {
		if (page == null) {
			return jdbcTemplate.query(queryAlbumsByUserIdWithoutPortraitSql, AlbumMapper.getMapper(), userId,
					authority, Activity.NORMAL.toString());
		}
		return this.getPaginationResult(queryAlbumsByUserIdWithoutPortraitSql, page, AlbumMapper.getMapper(), userId,
				authority, Activity.NORMAL.toString());
	}

	@Cache(keyPattern = "album-l-names-u:uid", type = CacheCategoryType.ALBUM)
	public List<Album> queryAlbumNamesOfUser(@Param("uid") @Fk long userId) {
		return jdbcTemplate.query(queryAlbumNamesOfUserSql, new RowMapper<Album>() {
			public Album mapRow(ResultSet rs, int rowNum) throws SQLException {
				Album album = new Album();
				album.setId(rs.getLong(AlbumMapper.COLUMN_ID));
				album.setAlbumName(rs.getString(AlbumMapper.COLUMN_ALBUM_NAME));
				album.setPhotoNum(rs.getInt(AlbumMapper.COLUMN_PHOTO_NUM));
				album.setCover(rs.getString(AlbumMapper.COLUMN_COVER));
				album.setCoverExt(rs.getString(AlbumMapper.COLUMN_COVER_EXT));
				return album;
			}
		}, userId, Activity.NORMAL.toString());
	}

	@Cache(keyPattern = "album-l-u:uid-act:act", type = CacheCategoryType.ALBUM)
	public List<Album> queryUserAlbumByActivity(@Param("uid") @Fk long userId, @Param("act") Activity activity) {
		return jdbcTemplate.query(queryUserAlbumByActivitySql, AlbumMapper.getMapper(), userId, activity.toString());
	}

	// public void updatePhotoCountDec(long albumId, int decCount) {
	// jdbcTemplate.update(updatePhotoCountDecSql, decCount, albumId);
	// }

	// @Cache(keyPattern = "album-d-:uid-:id", type = CacheCategoryType.ALBUM)
	// public Album queryUserAlbumDetailOfId(@Param("uid") long userId,
	// @Param("id") long albumId) {
	// List<Album> albums = jdbcTemplate.query(queryUserAlbumDetailOfIdSql,
	// AlbumMapper
	// .getMapper(), userId, albumId);
	// if (albums.isEmpty()) {
	// return null;
	// } else {
	// return albums.get(0);
	// }
	// }
	//
	// @Cache(keyPattern = "album-:uid-:id", type = CacheCategoryType.ALBUM)
	// public Album queryUserAlbumOfId(@Param("uid") long userId, @Param("id")
	// long albumId) {
	// List<Album> albums = jdbcTemplate.query(queryUserAlbumOfIdSql,
	// AlbumMapper.getMapper(),
	// userId, albumId);
	// if (albums.isEmpty()) {
	// return null;
	// } else {
	// return albums.get(0);
	// }
	// }

	/** -------------------华丽的分割线，下面的还没实现呢-------------------------------- **/
	// @Override
	// public int countUserAlbumOfId(long userId, long albumId) {
	// return this.getCountResult(countUserAlbumOfIdSql, userId, albumId);
	// }

	// @Override
	// public Album queryAlbumDetailById(long albumId) {
	// List<Album> albums = jdbcTemplate.query(queryAlbumDetailByIdSql,
	// AlbumMapper.getMapper(), albumId);
	// if (albums.isEmpty()) {
	// return null;
	// } else {
	// return albums.get(0);
	// }
	// }

	// @Override
	// public List<Album> queryActiveAlbumsByUserId(long userId, int authority,
	// Page page) {
	// return this.getPaginationResult(queryActiveAlbumsByUserIdSql, page,
	// AlbumMapper.getMapper(), userId, authority,
	// Activity.NORMAL.toString());
	// }
}
